import logging
import os
from logging.handlers import TimedRotatingFileHandler

from flask import Flask
from flask import jsonify
from flask import request

app = Flask(__name__)


@app.errorhandler(404)
def page_not_found(e):
	data = {
		'code': 404,
		'message': '错误信息:%s' % e
	}
	app.logger.error('%s' % e)
	return jsonify(data)


@app.errorhandler(405)
def page_method_not_allowed(e):
	data = {
		'code': 405,
		'message': '错误信息:%s' % e
	}
	app.logger.error('%s' % e)
	return jsonify(data)


@app.errorhandler(500)
def page_server_error(e):
	data = {
		'code': 500,
		'message': '错误信息:%s' % e
	}
	app.logger.error('%s' % e)
	return jsonify(data)


@app.route('/', methods=['POST'])
def hello_world():
	path = request.args.get('path')
	branch = request.get_json()['ref']
	# jsonStr = json.loads(request.get_json())
	# print(request.get_json()['ref'])
	# print(type(request.get_json()))
	# msg = "args:{0} get_json:{1}".format(str(request.args.to_dict()), str(request.get_json()))
	# app.logger.info('%s' % msg)
	os.chdir('/')
	if os.path.exists(path):
		os.chdir(path)
		res = os.popen("git pull origin HEAD:{0}".format(branch))
		message = ''
		for re in res.readlines():
			message += "{0}".format(re)
		data = {
			'code': 0,
			'message': message
		}
	else:
		data = {
			'code': 1,
			'message': '{0} 目录不存在！'.format(path)
		}
	return jsonify(data)


if __name__ == '__main__':
	app.debug = True
	formatter = logging.Formatter(
		"[%(asctime)s][%(filename)s:%(lineno)d][%(levelname)s][%(thread)d] - %(message)s")
	handler = TimedRotatingFileHandler(
		"flask.log", when="D", interval=1, backupCount=15,
		encoding="UTF-8", delay=False, utc=True)

	handler.setFormatter(formatter)
	app.logger.addHandler(handler)
	app.run(host="0.0.0.0", port=5000)
